#include "commoditydelegate.h"
#include "QDebug"
#include <QComboBox>
#include <QSqlTableModel>
#include <QCompleter>



QWidget *CommodityDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
            QComboBox *editor = new QComboBox(parent);
//            editor->addItem("Female");
//            editor->addItem("Famle");
//            editor->addItem("dd");
//            editor->addItem("ee");
            editor->setEditable(true);
            QSqlTableModel *model = new QSqlTableModel();
            model->setTable("wms_customer");
            model->select();
            editor->setModel(model);
            editor->setModelColumn(1);
            editor->completer()->setCompletionMode(QCompleter::PopupCompletion);
//            editor->installEventFilter(const_cast<CommodityDelegate *>(this));

//            connect(editor, SIGNAL(editingFinished()), this, SLOT(commitAndCloseEditor()));
            return editor;
}

void CommodityDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QComboBox *combo = qobject_cast<QComboBox *>(editor);
    combo->setCurrentText(index.data().value<QString>());
}

void CommodityDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QComboBox *combo = qobject_cast<QComboBox *>(editor);
    QSqlTableModel *tablemodel = static_cast<QSqlTableModel*>(model);
    int i = combo->currentIndex();
    QVariant var = combo->currentData(Qt::EditRole);
    QString str = var.value<QString>();
    qDebug() << var.typeName() << str;
    QAbstractItemModel *listmodel = combo->model();
    var = listmodel->data(listmodel->index(i, 1),Qt::EditRole);
    qDebug() << var;
    var = listmodel->data(listmodel->index(i, 0),Qt::EditRole);
    qDebug() << var;
    tablemodel->setData(index, listmodel->data(listmodel->index(i, 1),Qt::DisplayRole), Qt::DisplayRole);
    tablemodel->setData(index, listmodel->data(listmodel->index(i, 0),Qt::EditRole), Qt::EditRole);

}

//void CommodityDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
//{
//    QPoint a = option.rect.topLeft();
//    QPoint b = option.rect.bottomRight();
//    qDebug() << a <<  "," << b;

//    editor->setGeometry(QRect(a, option.rect.size()*5));
//}

//QSize CommodityDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
//{

//}
